﻿/*
* CRM_SMS.cs
*
* 功 能： N/A
* 类 名： CRM_SMS
*
* Ver    变更日期             负责人     变更内容
* ───────────────────────────────────
* V1.0  2015-06-23 18:38:21    黄润伟    
*
* Copyright (c) 2015 www.xhdcrm.com   All rights reserved.
*┌──────────────────────────────────┐
*│　版权所有：黄润伟                      　　　　　　　　　　　　　　│
*└──────────────────────────────────┘
*/

using System;
using System.Data;
using System.Web;
using XHD.Common;
using XHD.Controller;
using System.Collections.Generic;
using XHD.SMS;
using System.Threading;
using System.IO;

namespace XHD.Server
{
    public class CRM_SMS
    {
        public static BLL.sys_info info = new BLL.sys_info();
        public static BLL.CRM_SMS sms = new BLL.CRM_SMS();
        public static Model.CRM_SMS model = new Model.CRM_SMS();
        public static SMSHelper smshelper = new SMSHelper();

        public HttpContext Context;
        public int emp_id;
        public string emp_name;
        public Model.hr_employee employee;
        public HttpRequest request;
        public string uid;

        public string SerialNo;
        public string key;
        public string sms_done;


        public CRM_SMS()
        {
            DataSet ds = info.GetAllList();

            Dictionary<string, string> dic = new Dictionary<string, string>();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                dic.Add(ds.Tables[0].Rows[i]["sys_key"].ToString(), ds.Tables[0].Rows[i]["sys_value"].ToString());
            }
            SerialNo = dic["sms_no"];
            string enkey = dic["sms_key"];
            key = Common.DEncrypt.DESEncrypt.Decrypt(enkey);
            sms_done = dic["sms_done"];
        }

        public CRM_SMS(HttpContext context)
        {
            Context = context;
            request = context.Request;

            var userinfo = new User_info();
            employee = userinfo.GetCurrentEmpInfo(context);

            emp_id = employee.ID;
            emp_name = PageValidate.InputText(employee.name, 50);
            uid = PageValidate.InputText(employee.uid, 50);

            DataSet ds = info.GetAllList();

            Dictionary<string, string> dic = new Dictionary<string, string>();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                dic.Add(ds.Tables[0].Rows[i]["sys_key"].ToString(), ds.Tables[0].Rows[i]["sys_value"].ToString());
            }
            SerialNo = dic["sms_no"];
            string enkey = dic["sms_key"];
            key = Common.DEncrypt.DESEncrypt.Decrypt(enkey);
            sms_done = dic["sms_done"];
        }

        public double getBalance()
        {
            return smshelper.getBalance(SerialNo, key);
        }

        public string grid()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " id ";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = " desc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = "1=1";


            if (PageValidate.IsNumber(request["customerid"]))
                serchtxt += " and C_customerid=" + int.Parse(request["customerid"]);

            if (!string.IsNullOrEmpty(request["company"]))
                serchtxt += " and C_customername like N'%" + PageValidate.InputText(request["company"], 255) + "%'";

            if (!string.IsNullOrEmpty(request["contact"]))
                serchtxt += " and C_name like N'%" + PageValidate.InputText(request["contact"], 255) + "%'";

            if (!string.IsNullOrEmpty(request["tel"]))
                serchtxt += " and C_mob like N'%" + PageValidate.InputText(request["tel"], 255) + "%'";

            if (!string.IsNullOrEmpty(request["qq"]))
                serchtxt += " and C_QQ like N'%" + PageValidate.InputText(request["qq"], 255) + "%'";

            if (!string.IsNullOrEmpty(request["startdate"]))
                serchtxt += " and C_createDate >= '" + PageValidate.InputText(request["startdate"], 255) + "'";

            if (!string.IsNullOrEmpty(request["enddate"]))
            {
                DateTime enddate = DateTime.Parse(request["enddate"]).AddHours(23).AddMinutes(59).AddSeconds(59);
                serchtxt += " and C_createDate  <= '" + enddate + "'";
            }

            if (!string.IsNullOrEmpty(request["startdate_del"]))
                serchtxt += " and Delete_time >= '" + PageValidate.InputText(request["startdate_del"], 255) + "'";
            if (!string.IsNullOrEmpty(request["enddate_del"]))
            {
                DateTime enddate1 = DateTime.Parse(request["enddate_del"]).AddHours(23).AddMinutes(59).AddSeconds(59);
                serchtxt += " and Delete_time  <= '" + enddate1 + "'";
            }
            //权限           

            serchtxt += DataAuth();

            //context.Response.Write(serchtxt);

            DataSet ds = sms.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total);

            string dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);

            return dt;
        }

        public void save()
        {
            model.sms_title = PageValidate.InputText(request["T_title"], 255);
            model.sms_content = PageValidate.InputText(request["T_content"], int.MaxValue);
            string ids = PageValidate.InputText(request["ids"], int.MaxValue);
            ids = ids.Trim().TrimEnd(',');
            model.contact_ids = ids;

            string mobiles = PageValidate.InputText(request["mobiles"], int.MaxValue);
            mobiles = mobiles.Trim().TrimEnd(',');
            model.sms_mobiles = mobiles;

            model.dep_id = employee.d_id;
            model.create_id = emp_id;
            model.create_time = DateTime.Now;
            model.isSend = 0;

            int id = sms.Add(model);
        }
                
        public string send()
        {
            model.check_id = emp_id;
            model.isSend = 1;
            model.sendtime = DateTime.Now;
            string id = PageValidate.InputText(request["id"], 50);
            if (PageValidate.IsNumber(id))
            {
                model.id = int.Parse(id);


                DataSet ds = sms.GetList(string.Format("id={0}", id));
                DataRow dr = ds.Tables[0].Rows[0];

                string content = dr["sms_content"].ToString();
                string mobile = dr["sms_mobiles"].ToString();
                string[] mobiles = mobile.Split(',');

                int result = smshelper.sendSMS(SerialNo, key, mobiles, content, int.Parse(id));
                if (result == 0)
                {
                    sms.Update(model);
                }
                return SMSHelper.sms_result(result);
            }
            return "";
        }

        public void autoStatus()
        {
            if (sms_done == "1")
            {
                Model.Sys_SMS_reports modelreport = new Model.Sys_SMS_reports();
                BLL.Sys_SMS_reports report = new BLL.Sys_SMS_reports();
                SMS.SMS_Server.statusReport[] sr = smshelper.getReport(SerialNo, key);
                if (sr == null)
                {                    
                    return;
                }

                for (int i = 0; i < sr.Length; i++)
                {
                    modelreport.reportStatus = sr[i].reportStatus;
                    modelreport.mobile = sr[i].mobile;
                    modelreport.submitDate = sr[i].submitDate;
                    modelreport.receiveDate = sr[i].receiveDate;
                    modelreport.errorCode = sr[i].errorCode;
                    modelreport.memo = sr[i].memo;
                    modelreport.serviceCodeAdd = sr[i].serviceCodeAdd;
                    modelreport.seqID = Convert.ToInt64(sr[i].seqID.ToString());

                    report.Add(modelreport);
                }
            }
        }

        public string form(string id)
        {
            string dt;
            if (PageValidate.IsNumber(id))
            {
                DataSet ds = sms.GetList(string.Format("id = {0}", int.Parse(id)));
                dt = DataToJson.DataToJSON(ds);
            }
            else
            {
                dt = "{}";
            }
            return dt;
        }

        private string DataAuth()
        {
            //权限            
            string uid = employee.uid;
            string returntxt = "";

            if (uid != "admin")
            {
                {
                    var dataauth = new GetDataAuth();
                    string txt = dataauth.GetDataAuthByid("2", "Sys_view", emp_id);

                    string[] arr = txt.Split(':');
                    switch (arr[0])
                    {
                        case "none":
                            returntxt = " and 1=2 ";
                            break;
                        case "my":
                            returntxt = " and  create_id=" + arr[1];
                            break;
                        case "dep":
                            if (string.IsNullOrEmpty(arr[1]))
                                returntxt = " and  create_id=" + int.Parse(uid);
                            else
                                returntxt = " and  dep_id=" + arr[1];
                            break;
                        case "depall":
                            var dep = new BLL.hr_department();
                            DataSet ds = dep.GetAllList();
                            string deptask = GetTasks.GetDepTask(int.Parse(arr[1]), ds.Tables[0]);
                            string intext = arr[1] + "," + deptask;
                            returntxt = " and  dep_id in (" + intext.TrimEnd(',') + ")";
                            break;
                    }
                }
            }
            return returntxt;
        }
    }
}
